<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import {
  reqGetTrademarkList,
  reqGetSpuImageList,
  reqGetBaseSaleAttrList,
  reqGetHasSaleAttr,
  reqSaveOrUpdateSpuInfo,
} from "@/api/product/spu";
import { ElMessage } from "element-plus";
// computed计算属性
let unSelectSaleAttr = computed(() => {
  return baseSaleAttrList.value.filter((item: any) => {
    return hasSaleAttr.value.every((item1: any) => {
      return item.name != item1.saleAttrName;
    });
  });
});
const $emit = defineEmits(["updataScene"]);
// SPU的商品列表
let trademarkList = ref<any>([]);
// SPU图片
let spuImageList = ref<any>([]);
// SPU的全部销售属性
let baseSaleAttrList = ref<any>([]);
// 某一个SPU已有的销售属性
let hasSaleAttr = ref<any>([]);
// 控制dialog会话框的显示与隐藏的字段
let dialogVisible = ref<boolean>(false);
// dialog会话框要显示的图片
let dialogImageUrl = ref<string>("");
// 将来收集还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>("");
// 获取el-input的组件实例对象
let ipt = ref<any>();
// 发请求时需要的spu参数
let spuParams = ref<any>({
  category3Id: "",
  spuName: "",
  description: "",
  tmId: "",
  spuImageList: [],
  spuSaleAttrList: [],
});
// 点击取消按钮的回调
const cancel = () => {
  // 回到场景0
  $emit("updataScene", 0);
};
// 父组件点击修改SPU按钮的自定义事件
const initSpu = async (spu: any) => {
  spuParams.value = spu;
  let res1: any = await reqGetTrademarkList();
  if (res1.code == 200) {
    trademarkList.value = res1.data;
  }
  let res2: any = await reqGetSpuImageList(spu.id);
  if (res2.code == 200) {
    spuImageList.value = res2.data.map((item: any) => ({
      name: item.imgName,
      url: item.imgUrl,
    }));
  }
  let res3: any = await reqGetBaseSaleAttrList();
  if (res3.code == 200) {
    baseSaleAttrList.value = res3.data;
  }
  let res4: any = await reqGetHasSaleAttr(spu.id);
  if (res4.code == 200) {
    hasSaleAttr.value = res4.data;
  }
};
// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number) => {
  // 清空表单数据
  Object.assign(spuParams.value, {
    category3Id: "",
    spuName: "",
    description: "",
    tmId: "",
    spuImageList: [],
    spuSaleAttrList: [],
  });
  spuImageList.value = [];
  hasSaleAttr.value = [];
  saleAttrIdAndValueName.value = "";
  spuParams.value.category3Id = c3Id;
  let res1: any = await reqGetTrademarkList();
  if (res1.code == 200) {
    trademarkList.value = res1.data;
  }
  let res2: any = await reqGetBaseSaleAttrList();
  if (res2.code == 200) {
    baseSaleAttrList.value = res2.data;
  }
};
// 点击文件列表中已上传的文件时的钩子
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// el-upload照片墙上传成功前的钩子
const handler = (file: any) => {
  if (
    file.type == "image/png" ||
    file.type == "image/jpeg" ||
    file.type == "image/gif"
  ) {
    if (file.size / 1024 / 1024 > 5) {
      ElMessage({
        type: "error",
        message: "上传图片必须小于5MB",
      });
      return false;
    }
    return true;
  } else {
    ElMessage({
      type: "error",
      message: "上传文件必须是png|jpg|gif",
    });
    return false;
  }
};
// 添加销售属性的按钮的回调
const addSaleAttr = () => {
  const [saleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(":");
  //准备一个新的销售属性对象:将来带给服务器即可
  let newSaleAttr: any = {
    saleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  hasSaleAttr.value.push(newSaleAttr);
  //清空收集的数据
  saleAttrIdAndValueName.value = "";
};
// 点击添加销售属性值按钮的回调
const toEdit = (row: any) => {
  // 添加两个字段
  row.isEdit = true;
  row.saleAttrValue = "";
  nextTick(() => {
    ipt.value.focus();
  });
};
// input框失去焦点的回调
const toLook = (row: any) => {
  row.isEdit = false;
  let { baseSaleAttrId, saleAttrValue } = row;
  let newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  };
  // 判断不能为空
  if (saleAttrValue.trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空的",
    });
    return (row.flag = false);
  }
  // 判断属性值不能重复
  let repeat = row.spuSaleAttrValueList.find((item: any) => {
    return item.saleAttrValueName == saleAttrValue;
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值重复",
    });
    return (row.flag = false);
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  row.flag = false;
};
// 点击保存按钮的回调
const save = async () => {
  spuParams.value.spuImageList = spuImageList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  spuParams.value.spuSaleAttrList = hasSaleAttr.value;
  console.log(spuParams.value);
  let result = await reqSaveOrUpdateSpuInfo(spuParams.value);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: spuParams.value.id ? "更新成功" : "添加成功",
    });
    $emit("updataScene", 0);
  } else {
    ElMessage({
      type: "error",
      message: spuParams.value.id ? "更新失败" : "添加失败",
    });
  }
};

defineExpose({ initSpu, initAddSpu });
</script>
<script lang="ts">
export default {
  name: "SpuForm",
};
</script>

<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请输入SPU名称"
          v-model="spuParams.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select v-model="spuParams.tmId">
          <el-option
            v-for="item in trademarkList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="spuParams.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图标">
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="handler"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            alt="Preview Image"
            style="width: 100%; height: 100%"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select
          v-model="saleAttrIdAndValueName"
          :placeholder="
            unSelectSaleAttr.length
              ? `还有${unSelectSaleAttr.length}项未选择`
              : '无'
          "
        >
          <el-option
            v-for="item in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          @click="addSaleAttr"
          :disabled="saleAttrIdAndValueName ? false : true"
          >添加属性</el-button
        >
        <el-table border :data="hasSaleAttr" style="margin: 10px 0">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="销售属性名称"
            width="120px"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="销售属性值" width>
            <template v-slot="{ row, $index }">
              <el-tag
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="item.id"
                style="margin: 0 5px"
                :closable="true"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                >{{ item.saleAttrValueName }}</el-tag
              >
              <el-input
                v-model="row.saleAttrValue"
                v-if="row.isEdit == true"
                ref="ipt"
                @blur="toLook(row)"
                placeholder="请输入属性值"
                size="small"
                style="width: 100px"
              ></el-input>
              <el-button
                @click="toEdit(row)"
                v-else
                type="success"
                size="small"
                icon="Plus"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template v-slot="{ row, $index }">
              <el-button
                type="danger"
                icon="Delete"
                @click="hasSaleAttr.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="hasSaleAttr.length == 0 ? true : false"
          >保存</el-button
        >
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped></style>
